package com.foreveross.fetl.core.domain.freight.repository.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.mortbay.log.Log;
import org.springframework.stereotype.Repository;

import com.foreveross.fetl.common.HBaseTable;
import com.foreveross.fetl.common.hbase.client.HBaseHelper;
import com.foreveross.fetl.common.jpa.EntityHibernateRepository;
import com.foreveross.fetl.common.vo.model.Cabin;
import com.foreveross.fetl.core.domain.cabin.CabinGradeEntity;
import com.foreveross.fetl.core.domain.freight.AirChinaDomesticEntity;
import com.foreveross.fetl.core.domain.freight.repository.IAirChinaDomesticRepository;
import com.foreveross.fetl.core.domain.task.SourceEntity;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.HbaseToPlaneInfoUtil;
import com.foreveross.fetl.util.RowkeyUtils;
import com.foreveross.fetl.util.StringUtils;

@Repository("airChinaDomesticRepository")
public class AirChinaDomesticRepositoryImpl extends EntityHibernateRepository
		implements IAirChinaDomesticRepository {

	@Override
	public List<AirChinaDomesticEntity> findByCondition(Date reportDate,
			Date flightDate, String fromCity, String toCity, String flightNo,
			String carrierKey,String hbaseKey) {
		StringBuffer jpql =new StringBuffer("select airChina from AirChinaDomesticEntity airChina where 1=1 ");
		List<Object> conditionVals = new ArrayList<Object>();
		if(reportDate!=null){
			jpql.append(" and airChina.reportDate =? ");
			conditionVals.add(reportDate);
		}
		if(flightDate !=null){
			jpql.append(" and airChina.flightDate =? ");
			conditionVals.add(flightDate);
		}
		if(null!=fromCity && !"".equals(fromCity)){
			jpql.append(" and airChina.fromCity =? ");
			conditionVals.add(fromCity);
		}
		if(null!=toCity && !"".equals(toCity)){
			jpql.append(" and airChina.toCity =? ");
			conditionVals.add(toCity);
		}
		if(null!=flightNo && !"".equals(flightNo)){
			jpql.append(" and airChina.flightNo =? ");
			conditionVals.add(flightNo);
		}
		if(null!=hbaseKey && !"".equals(hbaseKey)){
			jpql.append(" and airChina.hbaseKey =? ");
			conditionVals.add(hbaseKey);
		}
		if(null!=carrierKey && !"".equals(carrierKey)){
			jpql.append(" and airChina.carrierKey =? ");
			conditionVals.add(carrierKey);
		}
	
		jpql.append(" order by airChina.creatTime desc ");
		return super.queryResult(jpql.toString(), conditionVals.toArray());
	}

	@Override
	public int creatReport(List<String> airCompanys, String fromCity,
			String toCity, Date reportDate, Date flightDate) {
		List<AirChinaDomesticEntity> listAirChina =new ArrayList<AirChinaDomesticEntity>();
		
		//价格集合
		Map<String,List<AirChinaDomesticEntity>> companyEntityMap = new HashMap<String,List<AirChinaDomesticEntity>>();
		for(String channel : airCompanys){
			companyEntityMap.put(channel, this.build(channel,  fromCity, toCity, reportDate, flightDate));
		}
		
		List<AirChinaDomesticEntity> tempAirChina = null;	
		for(String channel : airCompanys){
			tempAirChina=companyEntityMap.get(channel);
			if(null == tempAirChina)
				continue;
			for(AirChinaDomesticEntity en : tempAirChina){
				listAirChina.add(en);
			}
		
		}
		return this.saveList(listAirChina);
	}
	
	/**
	 * 根据抓取渠道查询Hbase
	 * @param channel
	 * @param areaCode
	 * @param fromCity
	 * @param toCity
	 * @param reportDate
	 * @param flightDate
	 * @return
	 */
	private List<AirChinaDomesticEntity> build(String channel, String fromCity,
			String toCity, Date reportDate, Date flightDate) {
		List<AirChinaDomesticEntity> listEntity =new ArrayList<AirChinaDomesticEntity>();
		String startRowKey =RowkeyUtils.getRowKey(reportDate, channel,  fromCity, toCity, flightDate, RowkeyUtils.START_ROW_KEY);
		String endRowKey=RowkeyUtils.getRowKey(reportDate, channel,  fromCity, toCity, flightDate, RowkeyUtils.STOP_ROW_KEY);
		ResultScanner rs = null;
		try {
			rs = HBaseHelper.getRecords(HBaseTable.BASE_DATA_FLIGHT,
					startRowKey, endRowKey,new String[]{"planeinfo","cabinsInfo"},null);
			for (Result res : rs) {
				AirChinaDomesticEntity en=this.buildAirSpread(res,channel,reportDate, flightDate);
				if(null!=en){
					listEntity.add(en);
				}
				
			}
		} catch (Exception e) {
			Log.info(StringUtils.getStackTrace(e));
		}finally{
			if(rs != null) rs.close();
			rs = null;
		}
		return listEntity;
	}
	
	/**
	 * 转换数据
	 * @param res
	 * @param channel
	 * @param reportDate
	 * @param flightDate
	 * @return
	 */
	private AirChinaDomesticEntity buildAirSpread(Result res, String channel,
			Date reportDate, Date flightDate) {
		Map<String, Map<String, String>> curMap = HBaseHelper
				.transformHBaseRowToMap(res);
		Map<String, String> curPalneInfoMap = curMap.get("planeinfo");
		if(curPalneInfoMap.get("flightId")==null) return null;
		if(curPalneInfoMap.get("flightId").indexOf("|")>0){
			curPalneInfoMap.put("flightId", curPalneInfoMap.get("flightId").substring(0, curPalneInfoMap.get("flightId").indexOf("|")));
		}
		if(curPalneInfoMap.get("flightId").indexOf(",")>0){
			curPalneInfoMap.put("flightId", curPalneInfoMap.get("flightId").substring(0, curPalneInfoMap.get("flightId").indexOf(",")));
		}
		String flightNo =curPalneInfoMap.get("flightId");
		
		String carrierKey =flightNo.substring(0, 2);
		
		boolean isCabins =false;
		isCabins =curMap.containsKey("cabinsInfo");

		if(!isCabins) return null;
		
		Map<String, String> cabinFCV = new HashMap<String,String>();// 保存HBASE中存储的信息
		cabinFCV=curMap.get("cabinsInfo");
		List<Cabin> cabins= HbaseToPlaneInfoUtil.getCabinsByMap(cabinFCV, 1);
		
		AirChinaDomesticEntity airChina =new AirChinaDomesticEntity();
		airChina.setHbaseKey(channel);
		airChina.setCarrierKey(carrierKey);
		airChina.setPrimePrice(this.getPrice(cabins, channel, "头等舱"));
		airChina.setBusinessPrice(this.getPrice(cabins, channel, "公务舱"));
		airChina.setEconomyPrice(this.getPrice(cabins, channel, "经济舱"));
		
		airChina.setReportDate(DateUtils.parse(DateUtils.format(reportDate, "yyyyMMdd"), "yyyyMMdd"));
		airChina.setFlightDate(DateUtils.parse(DateUtils.format(flightDate, "yyyyMMdd"), "yyyyMMdd"));
		airChina.setFromCity(curPalneInfoMap.get("fromCity"));
		airChina.setToCity(curPalneInfoMap.get("toCity"));
		airChina.setFromCityName(curPalneInfoMap.get("fromCityName"));
		airChina.setToCityName(curPalneInfoMap.get("toCityName"));
		airChina.setFlightNo(flightNo);
		return airChina;
	}
	
	 
	 /**
	  * 获得舱位级别的最低价
	  * @param cabins
	  * @param channel
	  * @param type
	  * @return
	  */
	 private Double getPrice(List<Cabin> cabins,String channel,String type){
		 List<String> listCabin =getCabinTypes(type,channel); //当前舱位级别包含的舱位列表
		 double price=0;
		 for(String str :listCabin){
			 for(Cabin cabin :cabins){
				 if(null==cabin.getPrice() || cabin.getPrice()==0)
					 continue;
				 String cabinType=cabin.getCabinType();
				 if(null==cabinType)
					 cabinType=cabin.getProductName();
				 if(null != cabinType&& ( cabinType.equals(str) || cabinType.indexOf(type)!=-1)){
						if(price==0 || price<1){
							price=cabin.getPrice();
						}else if(cabin.getPrice()!=0 && price>cabin.getPrice()){
							price=cabin.getPrice();
						}
				}
			 }
		 }
		 return price;
	 }
	 
	/**
	 * 获得该公司舱位级别对应的舱位 
	 * @param type
	 * @param channel
	 * @return
	 */
	private List<String> getCabinTypes(String type, String channel) {
		List<String> list =new ArrayList<String>() ;
		List<CabinGradeEntity> listCabinGrade =new ArrayList<CabinGradeEntity>();
		CabinGradeEntity cabinGradeEntity =new CabinGradeEntity();
		SourceEntity sourceEntity =new SourceEntity();
		List<SourceEntity> listsourceEntity=sourceEntity.findByHbaseKey(channel);
		if(null == listsourceEntity){
			return null;
		}
		listCabinGrade=cabinGradeEntity.listByType(listsourceEntity.get(0).getId());
		for(CabinGradeEntity entity :listCabinGrade){
			if(type.equals(entity.getUnifiedName())){
				list.add(entity.getName());
			}
		}
		return list;
	}
	

	
	/**
	 * 保存
	 * @param list
	 * @return
	 */
	private int saveList(List<AirChinaDomesticEntity> list){
		if(null!=list && list.size()>0){
			int i=0;
			for(AirChinaDomesticEntity entity: list){
				List<AirChinaDomesticEntity> oldList =new ArrayList<AirChinaDomesticEntity>();
				entity.setCreatTime(new Date());
				oldList=this.findByCondition(entity.getReportDate(), entity.getFlightDate(), entity.getFromCity(), entity.getToCity(), entity.getFlightNo(),null, entity.getHbaseKey());
				if(null!=oldList && !oldList.isEmpty()){
						AirChinaDomesticEntity oldAirChinaEntity =oldList.get(0);
						entity.setId(oldAirChinaEntity.getId());
						if(null ==entity.getPrimePrice() || entity.getPrimePrice()==0 ){
							entity.setPrimePrice(oldAirChinaEntity.getPrimePrice());
						}
						
						if( null ==entity.getBusinessPrice() || entity.getBusinessPrice() == 0){
							entity.setBusinessPrice(oldAirChinaEntity.getBusinessPrice());
						}
					
						if( null == entity.getEconomyPrice() || entity.getEconomyPrice() == 0){
							entity.setEconomyPrice(oldAirChinaEntity.getEconomyPrice());
						}
				}
				this.save(entity);
				i++;
			}
			return i;
		}
		return 0;
	}

	 
}
